# coding: utf-8
class ArticlesController < ApplicationController
  include ArticlesHelper
  include ApplicationHelper

  #attr_accessor :category_id
  before_action :set_article, only: [:show, :edit, :update, :destroy]


  skip_before_action :authorize, only: [:index, :show]

  #before_action :authorize, only: [:new, :create, :destroy]
  #before_action :logged_in_user, only: [:new, :create, :destroy] # 只有登录才能删除用户

  # GET /articles
  # GET /articles.json
  def index
    #@tags = Article.group(:category_id).count

    if params[:query].present?
        @articles = Article.search(params[:query])
    else  
        @articles = Article.order('created_at').page(params[:page])
    end
  end

  # GET /articles/1
  # GET /articles/1.json
  def show
  end

  # GET /articles/new
  def new
    @article = Article.new
  end

  # GET /articles/1/edit
  def edit
  end

  # POST /articles
  # POST /articles.json
  def create
    @article = Article.new(article_params)
    @article.user_id = session[:user_id]

    respond_to do |format|
      if @article.save
        flash[:success] = "创建成功"
        format.html { redirect_to @article}
        format.json { render :show, status: :created, location: @article }
      else
        format.html { render :new }
        format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /articles/1
  # PATCH/PUT /articles/1.json
  def update
    respond_to do |format|
      if @article.update(article_params)
        flash[:success] = "修改成功"
        format.html { redirect_to @article}
        format.json { render :show, status: :ok, location: @article }
      else
        format.html { render :edit }
        format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /articles/1
  # DELETE /articles/1.json
  def destroy
    @article.destroy
    respond_to do |format|
      flash[:danger] = "文章已删除"
      format.html { redirect_to admin_articles_path }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_article
      @article = Article.find(params[:id])
    end

    # 白名单
    def article_params
      params.require(:article).permit(:content, :user_id, :title, :category_id)
    end
end
